import { Component, OnInit } from '@angular/core';
import {IonicPage, PopoverController, ToastController} from 'ionic-angular';
import {Router} from"@angular/router";
import {Location} from '@angular/common';
import {Platform} from 'ionic-angular';
// 引入自定义的服务
import {HttphandleProvider} from '../../providers/httphandle/httphandle';
import {LocalstorageProvider} from '../../providers/localstorage/localstorage';
import {ActionsType} from './actionstype';
import {QrcodeshowPage} from '../qrcodeshow/qrcodeshow';
import { AlertController } from 'ionic-angular';
import { Brightness } from '@ionic-native/brightness';
import { Tools } from '../../tools/tools';
import { NativePageTransitions } from '@ionic-native/native-page-transitions';
import { Network } from '@ionic-native/network';

/**
 * Generated class for the HomePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage extends Tools implements OnInit{

  private username: string;
  actions: Array<ActionsType> = [];
  private popover: any;
  private errorState: any;
  private homeList: any = null;
  private userInfo:any = null;
  constructor(private location: Location,
              private http: HttphandleProvider,
              private loc: LocalstorageProvider,
              private popoverCtrl: PopoverController,
              public alertCtrl: AlertController,
              private brightness: Brightness,
              private toastCtrl: ToastController,
              protected nativePageTransitions: NativePageTransitions,
              protected route: Router,
              protected network: Network,
              public platform: Platform
            ) {
    super(route, nativePageTransitions, network)
    this.route.onSameUrlNavigation = 'reload'
    // 信息获取
    this.homeList = this.loc.get('homeData')
    this.userInfo = this.loc.get('userinfo')
  }

  ngOnInit(): void {
    var token = this.loc.get('token')
    // 异常判断 token
    if (!token) {
      this.openPage('login')
      return
    }
    // 获取用户信息判断是否存在该用户
    if (!this.userInfo) {
      this.httpPersonal();
    } else {
      this.username = this.userInfo['worker_name'];
    }
    // 菜单
    if (!this.homeList || this.homeList.length == 0) {
      this.menuPermissions();
    }
    // 获取之前的亮度 进行保存
    if (this.isMobile()) {
      this.brightness.getBrightness().then((res) => {
        this.loc.set('defaultBrightness',res)
      });
    }
  }

  doRefresh(refresher){
    if (!this.homeList || this.homeList.length == 0) {
      console.log('下拉刷新获取菜单信息')
      this.menuPermissions(refresher)
    } else if (!this.userInfo) {
      console.log('下拉刷新获取个人信息')
      this.httpPersonal(refresher)
    } else {
      // 无需刷新  关闭刷新
      setTimeout(() => {
        refresher && refresher.complete()
      }, 1000)
    }
  }

  menuPermissions(refresher?) {
    let that = this
    this.http.get('/app/rest/v2/services/yes_AppLoginPermissionService/menuPermission').then(res => {
      console.log('获取菜单信息',res)
      setTimeout(() => {
        refresher && refresher.complete()
      }, 1000)
      if(res){
        this.MenuShow(res);
      }
    }).catch(err => {
      setTimeout(() => {
        refresher && refresher.complete()
      }, 1000)
      console.log('获取菜单信息',err)
      if (err.status === 401) {
        this.http.getToken((res) => {
          this.loc.set('token', res.json())
          this.menuPermissions(refresher)
        })
      } else {
        var toast = this.toastCtrl.create({
          message: err.errMsg || err,
          position: 'top',
          duration: 1000
        })
        toast.present()
        // 获取菜单信息错误 ，重新登录
        toast.onDidDismiss(() => {
          that.goLogin()
        })
      }
    })
  }
  // 是否是真机环境
  isMobile(): boolean {
    return this.platform.is("mobile") && !this.platform.is("mobileweb");
  }


  httpPersonal(refresher?) {
    this.http.get('/app/rest/v2/services/yes_StaffInfoService/getStaffInfo').then(res => {
      setTimeout(() => {
        refresher && refresher.complete()
      }, 1000)
      console.log('获取用户信息',res)
      this.username = res['worker_name'];
      this.loc.set('userinfo', res)
      this.userInfo = res
      if (res.error) {
        this.errorState = res.error;
        this.showConfirm();
      }
    }).catch(err => {
      setTimeout(() => {
        refresher && refresher.complete()
      }, 1000)
      console.log('获取用户信息',err)
      if (err.status === 401) {
        this.http.getToken((res) => {
          this.loc.set('token', res.json())
          this.httpPersonal()
        })
      } else {
        this.toastCtrl.create({
          message: err.errMsg || err,
          position: 'top',
          duration: 1000
        }).present()
        console.log("服务器或网络", err)
      }
    })
  }


  goSettings() {
    this.openPage('settings')
  }

  goPersonal() {
    this.openPage('person')
  }

  back() {
    this.location.back()
  }

  goLogin() {
    this.openPage('login')
  }

  showConfirm() {
    let confirm = this.alertCtrl.create({
      title: '提示',
      message: this.errorState,
      buttons: [
        {
          text: '确定',
          handler: () => {
            this.loc.remove("token");
            if (!this.loc.remove("token")) {
              this.openPage('login')
            }
          }
        }
      ]
    });
    confirm.present();
  }

  actionhandler(str) {
    if (str == 'showqrcode') {
      this.brightness.setBrightness(1);
      this.popover = this.popoverCtrl.create(QrcodeshowPage, {}, {
        cssClass: 'qrcodewraper',
        showBackdrop: true,
        enableBackdropDismiss: true
      });
      this.popover.present();
    } else {
      this.openPage(str)
    }
  }

  MenuShow(res) {
    let dataHome = [];
    let pressions;
    if (res.length) {
      pressions = res;
    } else {
      pressions = Object.keys(res)
    }
    for (let j = 0; j < pressions.length; j++) {
      switch (pressions[j]) {
        case "first":
        case "手持终端登录":
            dataHome.push({
              name: '手持终端登录',
              img: './assets/imgs/icon5.png',
              url: 'showqrcode'
            });
          break;
        case "second":
        case "生产订单":
            dataHome.push({
              name: '生产单',
              img: './assets/imgs/icon2.png',
              url: 'productOrder'
            });
          break;
        case "third":
        case "生产监控":
            dataHome.push({
              name: '生产监控',
              img: './assets/imgs/icon7.png',
              url: 'lineAttendance'
            });
          break;
        case "fourth":
        case "生产统计":
            dataHome.push({
              name: '生产统计',
              img: './assets/imgs/icon8.png',
              url: 'productStatistics'
            });
          break;
      }
    }
    // if (res.length == 1) {
    //   dataHome = [{name: res[0], img: './assets/imgs/icon5.png', url: 'showqrcode'}];
    // } else if (res.length == 2) {
    //   dataHome = [
    //     {name: res[0], img: './assets/imgs/icon5.png', url: 'showqrcode'},
    //     {name: res[1], img: './assets/imgs/icon2.png', url: 'productOrder'},
    //   ];
    // } else if (res.length == 3) {
    //   dataHome = [
    //     {name: res[0], img: './assets/imgs/icon5.png', url: 'showqrcode'},
    //     {name: res[1], img: './assets/imgs/icon2.png', url: 'productOrder'},
    //     {name: res[2], img: './assets/imgs/icon7.png', url: 'lineAttendance'},
    //   ];
    // } else if (res.length == 4) {
    //   dataHome = [
    //     {name: res[0], img: './assets/imgs/icon5.png', url: 'showqrcode'},
    //     {name: res[1], img: './assets/imgs/icon2.png', url: 'productOrder'},
    //     {name: res[2], img: './assets/imgs/icon7.png', url: 'lineAttendance'},
    //     {name: res[3], img: './assets/imgs/icon8.png', url: 'productStatistics'},
    //   ]
    // }
    this.homeList = dataHome;
    this.loc.set('homeData', dataHome);
  }

}
